﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
//using MySql.Data.MySqlClient;

namespace Platform.Storage.Entity
{

	/// <summary>
	/// Contexto para acessar o banco de dados através do Entity Framework
	/// </summary>
	internal sealed class DataObjectContext : DbContext
	{

		public DataObjectContext()
			: base( GetConnection(), GetModel(), true )
		{
			this.Configuration.AutoDetectChangesEnabled = false;
			this.Configuration.LazyLoadingEnabled = false;
			this.Configuration.ProxyCreationEnabled = false;

			
			this.Fields = this.Set<FieldValue>();
			this.Relationships = this.Set<DataObjectRelationship>();
			//this.DateTimeIndexes = this.Set<FieldDateTimeIndex>();
		}

		public DbSet<FieldValue> Fields
		{ get; private set; }

		public DbSet<DataObjectRelationship> Relationships
		{ get; private set; }

		//public DbSet<FieldDateTimeIndex> DateTimeIndexes
		//{ get; private set; }

		protected override void OnModelCreating( DbModelBuilder modelBuilder )
		{
			base.OnModelCreating( modelBuilder );
		}

		/// <summary>
		/// Obtém o mapeamento entre o modelo e o banco de dados
		/// </summary>
		/// <returns></returns>
		private static DbCompiledModel GetModel()
		{

			var builder = new DbContextModelBuilder();
			var model = builder.Build( GetConnection() );
			return model.Compile();
		}

		/// <summary>
		/// Obtém a conexão com o banco de dados
		/// </summary>
		/// <returns></returns>
		private static DbConnection GetConnection()
		{
			// return null;
			return new System.Data.SqlClient.SqlConnection( ConfigurationManager.ConnectionStrings[ "AppDB" ].ConnectionString );
			// TODO : Melhorar a maneira de como é criada a conexão com o banco de dados
			//return new MySqlConnection( ConfigurationManager.ConnectionStrings[ "AppDB" ].ConnectionString );
		}
	}
}
